﻿using System.Reflection;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.ByteCode.Castle;
using BonsaiScrum.Data.Mappings;

namespace BonsaiScrum.Data
{
    public class NHibernateSessionSource : ISessionSource
    {
        private ISessionFactory _sessionFactory;

        private ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                {
                    _sessionFactory = Fluently.Configure()
                        .Database(
                            JetDriverConfiguration.Standard
                                .ShowSql()
                                .FormatSql()
                                .ConnectionString(x =>
                                    {
                                        x.DatabaseFile("../BonsaiScrum.mdb");
                                        x.Provider("Microsoft.Jet.OLEDB.4.0");
                                    })
                                .ProxyFactoryFactory<ProxyFactoryFactory>()
                        )
                        .Mappings(m =>
                            {
                                m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly());
                                m.HbmMappings.AddFromAssembly(Assembly.GetExecutingAssembly());
                            })
                        .BuildSessionFactory();
                }

                return _sessionFactory;
            }
        }

        public ISession CreateSession()
        {
            return SessionFactory.OpenSession();
        }
    }
}
